package org.starapp.rbac.action;

import javax.validation.Valid;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.starapp.rbac.entity.Users;
import org.starapp.rbac.service.UsersService;

/**
 * 帐户管理：
 * 		帐户名是否存在
 * 		注册帐户
 * 		修改帐户信息
 * 		
 * 		
 * @author 王强
 *
 */
@Controller
@RequestMapping(value = "/account")
public class AccountController {
	@Autowired
	private UsersService usersService;
	
	/**
	 * 帐户名是否存在
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "checkLoginName")
	@ResponseBody
	public String checkLoginName(@RequestParam("userId") String userId) {
		return usersService.getUsers(userId)==null?"true":"false";
	}
	
	/**
	 * 跳转注册帐户页面
	 * @return
	 */
	@RequestMapping(value = "register",method = RequestMethod.GET)
	public String registerForm() {
		return "account/register";
	}

	/**
	 * 注册帐户
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "register",method = RequestMethod.POST)
	public String register(Users user, RedirectAttributes redirectAttributes) {
		usersService.saveUsers(user);
		redirectAttributes.addFlashAttribute("userId", user.getUserId());
		return "redirect:/login";
	}
	
	/**
	 * 跳转到修改帐户信息页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="update",method = RequestMethod.GET)
	public String updateForm(Model model) {
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		String userId = user.getUserId();
		model.addAttribute("user", usersService.getUsers(userId));
		return "account/profile";
	}

	/**
	 * 修改帐户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value="update",method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadUser") Users user) {
		usersService.updateUsers(user);
		Users u = (Users) SecurityUtils.getSubject().getPrincipal();
		u.setUserName(user.getUserName());
		return "redirect:/";
	}

	/**
	 * 预加载帐户信息
	 * 			
	 * 			使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,
	 * 			先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 			因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 * @param userId
	 * @return
	 */
	@ModelAttribute("preloadUser")
	public Users getUser(@RequestParam(value = "userId", required = false) String userId) {
		if (userId != null) {
			return usersService.getUsers(userId);
		}
		return null;
	}
}
